import Vue from 'vue'
import Vuex from 'vuex'
import setRouter from './modules/setRouter'
import tabs from './modules/tabs'
import {decodeJWT, getToken, setIdToken, setRefreshToken} from "@/utils/oAuth2Login";
import {setUserInfo} from "@/api/user";

Vue.use(Vuex)
const getDefaultStateSSO = () => ({
    token: localStorage.getItem('token') ? localStorage.getItem('token') : '',
    refresh_token: localStorage.getItem('refresh_token') ? localStorage.getItem('refresh_token') : '',
    userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : '',
})
const store = new Vuex.Store({
    state: getDefaultStateSSO(),
    getters: {},
    mutations: {
        SET_TOKEN: (state, data) => {
            const { token, refresh_token } = data
            Object.assign(state, data)
            setIdToken(token)
            setRefreshToken(refresh_token)
        },
        SET_USER_INFO: (state, userInfo) => {
            state.userInfo = userInfo
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
        },
    },
    actions: {
        // scm token
        getJwtToken({dispatch, commit}, code) {
            return new Promise((resolve => {
                getToken(code).then(async res => {
                    if (res.data.id_token) {
                        const {
                            id_token: token,
                            refresh_token,
                        } = res.data
                        const obj = {
                            token,
                            refresh_token,
                        }
                        commit('SET_TOKEN', obj) // 后端接口调用 ，使用 id_token
                        await setUserInfo({
                            sysId: '6573743B-E431-4FDE-8D82-2FEAF96AEF6A',
                            userName: decodeJWT(token).preferred_username
                        }).then(info => {
                            if (info.data.code === 200) {
                                const { exp } = decodeJWT(token)
                                commit('SET_USER_INFO', Object.assign(info.data.data, { exp }))
                                resolve({ ...obj, ...info.data.data })
                            } else {
                                resolve(false)
                            }
                        })
                    } else {
                        resolve(false)
                    }
                }).catch(err => {
                    resolve(false)
                })
            }))
        },
    },
    modules: {
        setRouter,
        tabs
    }
})
export default store